<template>
  <div class="add-wrap">
    <div class="add-wrap__haschose">
      <div class="folder-tree">
        <a-menu
          mode="inline"
          :open-keys="openKeys"
          style="width: 300px"
          @openChange="onOpenChange"
        >
          <a-sub-menu v-for="(item, index) in rootSubmenus" :key="item.title">
            <span slot="title">
              <a-icon type="database" />
              <span>{{ item.title }}</span>
              <div class="actions">

                <a-tooltip title="remove database">
                  <a-button
                    type="link"
                    class="addfile"
                    @click.stop="showDeleteConfirm(item, index)"
                  >
                    <a-icon type="delete" />
                  </a-button>
                </a-tooltip>

              <a-tooltip title="新建查询">
                <a-button
                  type="link"
                  class="editfnname"
                  @click.stop="showDrawer(item)"
                >
                  <a-icon type="edit" />
                </a-button>
              </a-tooltip>
              </div>
            </span>

            <a-menu-item
              :key="index + table.tableName"
              v-for="(table, index) in item.tables"
              @click="loadTable(item.title, table.tableName)"
              class="ant-menu-submenu-title"
            >
              <a-icon type="table" /><span>{{ table.tableName }}</span>

              <div class="actions" style="margin-right: -30px;">
                <a-tooltip :title="'新建查询 '+table.tableName">
                  <a-button
                      type="link"
                      class="editfnname"
                      @click.stop="showDrawer(item,table)"
                    >
                      <a-icon type="edit" />
                    </a-button>
                </a-tooltip>
              </div>

              <!-- <a-menu-item
                :key="table.tableName + field.field"
                v-for="field in table.fields"
              >
               
              </a-menu-item> -->

            </a-menu-item>
          </a-sub-menu>
        </a-menu>
      </div>

      <div class="add-wrap__edit" v-show="columns.length">
        <a-spin :spinning="spinning">
          <a-table
            bordered
            :columns="columns"
            :data-source="datas"
            :loading="spinning"
            :scroll="scroll"
            @change="handleTableChange"
            :pagination="pagination"
          >
            <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
              <pre>{{ record }}</pre>
            </p>
          </a-table>
        </a-spin>
      </div>

      <a-drawer
        width="800px"
        placement="right"
        :closable="false"
        :visible="drawerVisible"
        @close="hideDrawer"
      >
      
        
        <div :style="editresult">
          <Editor class="editor-wrap" language="json" :readOnly="true" @editorDidMount="didMountResult"></Editor>
        </div>
        <a-button @click="runSQL()" style="margin-top:20px">运行 (F5)</a-button>
        <a-divider />
        <div :style="editsql">
          <Editor class="editor-wrap" language="sql" @editorDidMount="didMountEdit" @runf5="runSQL"></Editor>
        </div>
        
      </a-drawer>

    </div>
  </div>
</template>

<script>

import Editor from "@/components/editor.vue";

export default {
  components: {
    Editor
  },
  data() {
    return {
      editorEdit:{},
      editorResult:{},
      drawerVisible: false,
      thatSQLTitle: "",
      editsql:{
        height:(document.body.clientHeight*0.38)+"px",
        width:"750px"
      },
      editresult:{
        height:(document.body.clientHeight*0.45)+"px",
        width:"750px"
      },

      openKeys: [],
      rootSubmenus: [],
      scroll: { x: "70%", y: 600 },
      spinning: false,

      pagination: {
        total: 20,
        title: "",
        tableName: ""
      },

      columns: [],
      datas: []
    };
  },
  created() {

    var that = this;
    this.spinning = true;
    this.$cloud
      .command("iTool Database GetList")
      .then(res => {
        this.spinning = false;

        console.log(res);

        for (const key in res) {
          const value = res[key];

          that.datas.push({
            title: key,
            connaction: value
          });

          this.rootSubmenus = [];

          for (let index = 0; index < res.length; index++) {
            const element = res[index];

            if (index == 0) {
              this.openKeys = [element.title];
            }

            var db = {
              title: element.title,
              tables: []
            };

            for (const tableName in element.tableInfo) {
              const fields = element.tableInfo[tableName];
              db.tables.push({
                tableName: tableName,
                fields: fields
              });
            }

            this.rootSubmenus.push(db);

            console.log(this.rootSubmenus);
          }
        }
      })
      .catch(error => {
        this.spinning = false;
        console.error(error);
      });
  },
  methods: {

    runSQL:function(){
      const code = this.editorEdit.getValue();

      this.$cloud.command("iTool Excuted Sql",{
        Title: this.thatSQLTitle,
        Sql: code
      })
      .then(res => {
        console.log(res)
        this.editorResult.setValue(
          JSON.stringify(res, null, "\t")
          );
      }).catch(error=> {
        console.log(error)
        this.editorResult.setValue(
          JSON.stringify(error, null, "\t")
          );
      });
    },

    onOpenChange(openKeys) {
      const latestOpenKey = openKeys.find(
        key => this.openKeys.indexOf(key) === -1
      );
      this.openKeys = latestOpenKey ? [latestOpenKey] : [];
    },

    showDrawer(item,table) {
      this.drawerVisible = true;
      this.thatSQLTitle = item.title;

      if (table) {
        setTimeout(function(){
          var fields = table.fields.map(field => {
            return `[${field.field}]`;
          });
          const code = `select top 10 \n\t${fields.join(',\n\t')} \nfrom \n\t${table.tableName} \norder by 1 asc`;
          this.editorEdit.setValue(code);
        }.bind(this),this.editorEdit ? 1 : 500)
      }

    },
    hideDrawer() {
      this.drawerVisible = false;
    },

    didMountEdit(editor) {
      this.editorEdit = editor;
      const code = `-- input sql\n`;
      this.editorEdit.setValue(code);
    },
    didMountResult(editor) {
      this.editorResult = editor;
    },

    handleTableChange(p, filters, sorter) {
      console.log(p, filters, sorter);
      this.loadTable(
        this.pagination.title,
        this.pagination.tableName,
        p.current,
        sorter.field,
        (sorter.order || "").replace("end", "")
      );
    },

    loadTable(title, tableName, page, field, orderby) {
      this.spinning = true;

      this.pagination.title = title;
      this.pagination.tableName = tableName;

      var script = {};

      script["[]"] = {
        count: 12,
        page: page ? page : 1,
        query: 2
      };

      script["[]"][tableName] = {};

      if (field) {
        script["[]"][tableName]["@order"] =
          orderby == "asc" ? field + "+" : field + "-";
      }

      script["total@"] = "/[]/total";

      console.log(script);

      this.$cloud
        .command("iTool APIJSON", {
            MothodType: "get",
            Script: JSON.stringify(script),
            Connaction: {
              Title: title
            }
          })
        .then(res => {
          var data = JSON.parse(res);
          // console.log(res);

          this.spinning = false;

          var tableData = data["[]"];
          this.columns = [];
          this.datas = [];

          console.log(data.total);

          this.pagination.total = data.total;
          this.pagination["show-total"] = (total, range) =>
            `${range[0]}-${range[1]} of ${total} items`;
          this.pagination["pageSize"] = 12;
          this.pagination["defaultCurrent"] = 1;

          for (let index = 0; index < tableData.length; index++) {
            const row = tableData[index];

            if (index == 0) {
              for (const key in row[tableName]) {
                this.columns.push({
                  title: key,
                  dataIndex: key,
                  defaultSortOrder: "descend",
                  sorter: (a, b) => a.age - b.age,
                  ellipsis: true
                });
              }
            }

            this.datas.push(row[tableName]);
          }
        });
    },

    showDeleteConfirm(item, index){
      console.log(item);
      var that = this
      this.$confirm({
              title: 'Are you sure delete this database?',
              content: '删除后将从数据库列表中移除',
              okText: 'Yes',
              okType: 'danger',
              cancelText: 'No',
              onOk() {
                that.deleteItem(item, index);
              },
              onCancel() {
              },
            });
    },

    deleteItem(item, index) {

      var that = this;
      this.spinning = true;

      this.$cloud
        .command("iTool Database Remove", {
            Title: item.title
          })
        .then(res => {
          console.log(res);
          this.spinning = false;

          that.rootSubmenus.splice(index, 1);

          for (var i = 0; i < that.datas.length; i++) {
            if (that.datas[i].title == item.title) {
              that.datas.splice(i, 1);
            }
          }

          this.$message.success("提交成功");
        })
        .catch(error => {
          this.spinning = false;
          console.log(error);
        });
    }
  }
};
</script>

<style lang="less">
.editor-wrap,
.monaco-editor .overflow-guard,
.monaco-editor, .monaco-editor .inputarea.ime-input{
  width: 100% !important;
  flex: 1;
}

.add-wrap .add-wrap__haschose .folder-tree .ant-menu-item{
  font-size: 12px;
  background: white !important;
}

.add-wrap {
  height: 100%;
  .add-wrap__haschose {
    display: flex;
    height: 100%;
    .folder-tree {
      .ant-menu-submenu-title {
        background: #eee;
        margin: 0;
        .actions {
          display: none;
          float: right;
          .ant-btn {
            padding: 0;
            border: none;
          }
        }
        &:hover {
          .actions {
            display: block;
          }
        }
      }
      .ant-menu-item {
        margin: 0;
      }
    }
    .add-wrap__edit {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: 100%;
      margin-left: 10px;
      .editor-wrap {
        margin-top: 10px;
        flex: 1;
        overflow: hidden;
      }
      .actions {
        margin-top: 10px;
        .ant-btn {
          margin-right: 10px;
        }
      }
    }
  }
  .add-wrap__dochose {
    display: flex;
    flex-direction: column;
    .title {
      font-size: 18px;
      text-align: center;
      line-height: 50px;
    }
    .modes {
      flex: 1;
      display: flex;
      padding-top: 100px;
      flex-direction: row;
      justify-content: center;
      .mode-item {
        border: 1px solid #eee;
        border-radius: 4px;
        width: 240px;
        height: 320px;
        text-align: center;
        cursor: pointer;
        line-height: 320px;
        &.onlineedit {
          margin-right: 100px;
        }
      }
    }
  }
}
</style>
